package com.example.Mysql;

import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * Http请求工具类
 * @author 吴志鑫
 */
public class HttpUtil {

    /**
     * 发送Post请求(带请求头数据)
     * @param url 请求url
     * @param params 请求参数map集合
     * @param headers 请求头参数map集合
     * @return 响应对象
     * @param <T> 请求参数值类型
     */
    public static <T> HttpResponse sendPost(String url, Map<String, T> params, Map<String, String> headers) {
        // 创建Httpclient对象
        HttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 请求对象，如果是Get请求就用HttpGet
        HttpPost httpPost = new HttpPost(url);


        if (params != null){
            // 将 params 转换为 JSON 格式的字符串
            String json = new Gson().toJson(params);

            StringEntity requestEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);
        }

        // 发送请求并获取响应
        try {
            return httpClient.execute(httpPost);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送GET请求
     * @param url 请求路径
     * @param params 请求参数的map集合
     * @return 响应对象
     */
    public static HttpResponse sendGet(String url, Map<String, String> params, Map<String, String> headers) {

        // 创建Httpclient对象
        HttpClient httpClient = HttpClients.createDefault();

        String finalUrl = url;
        if(params != null){
            try {
                // 构建带有参数的 URI
                URIBuilder builder = new URIBuilder(url);
                params.forEach(builder::addParameter);
                finalUrl = builder.build().toString();
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
        }

        // 创建 HttpPost 请求对象，如果是Get请求就用HttpGet
        HttpGet httpGet = new HttpGet(finalUrl);

        if (headers != null && !headers.isEmpty()){
            // 设置请求头
            headers.forEach(httpGet::setHeader);
        }

        // 发送请求并获取响应
        try {
            // 发送请求并获取响应
            return httpClient.execute(httpGet);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
